<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>销售管理</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/lib/layui-v2.5.5/css/layui.css" media="all">
    <link rel="stylesheet" href="/css/public.css" media="all">
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">
      <!--搜索开始-->
      <fieldset class="layui-elem-field layuimini-search">
        <legend>搜索信息</legend>
        <div style="margin: 10px 10px 10px 10px">
          <form class="layui-form layui-form-pane" action="" id="searchFrm">
            <div class="layui-form-item">
              <div class="layui-inline">
                <label class="layui-form-label">客户</label>
                <div class="layui-input-inline">
                  <select name="customerId" class="customerSel">
                    <option value ="">请选择客户</option>
                  </select>
                </div>
              </div>
              <div class="layui-inline">
                <label class="layui-form-label">商品名称</label>
                <div class="layui-input-inline">
                  <input type="hidden" name="id" />
                  <select name="goodsId" id="data_goodsid" class="goodsSel">
                    <option value ="">请选择商品</option>
                  </select>
                </div>
              </div>
              <div class="layui-inline">
                <label class="layui-form-label">开始时间</label>
                <div class="layui-input-inline">
                  <input type="text" name="startTime" id="startTime" readonly="readonly" autocomplete="off" class="layui-input">
                </div>
              </div>
              <div class="layui-inline">
                <label class="layui-form-label">结束时间</label>
                <div class="layui-input-inline">
                  <input type="text" name="endTime" id="endTime" readonly="readonly" autocomplete="off" class="layui-input">
                </div>
              </div>
            </div>
            <div class="layui-form-item">
              <div class="layui-block" style="text-align: center;">
                <a class="layui-btn " lay-submit=""  lay-filter="data-search-btn"><label class="layui-icon layui-icon-search"></label>搜索</a>
                <a class="layui-btn layui-btn-warm" onclick="javascript:$('#searchFrm')[0].reset()" lay-filter="data-search-btn"><label class="layui-icon layui-icon-refresh"></label>重置</a>
              </div>
            </div>
          </form>
        </div>
      </fieldset>
      <!--搜索结束-->

      <script type="text/html" id="enableTpl">
        <input type="checkbox" name="enable" value="{{d.id}}" lay-skin="switch" lay-text="是|否" lay-filter="enableSwitch" {{ d.enable == 1 ? 'checked' : '' }}>
      </script>

      <script type="text/html" id="toolBar">
        <div class="layui-btn-group">
          <a class="layui-btn layui-btn-sm data-count-add" lay-event="add">添加</a>
          <a class="layui-btn layui-btn-sm data-count-delete" lay-event="delete">删除</a>
        </div>
      </script>
      <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>

      <script type="text/html" id="tableBar">
        <a class="layui-btn layui-btn-xs layui-btn-danger data-count-update" lay-event="back">退货</a>
      </script>

      <!--添加和修改的弹出层开始-->
      <div id="addOrUpdateDiv" style="display: none;padding: 0.3125rem">
        <form method="post" class="layui-form layui-form-pane" lay-filter="dataFrm" id="dataFrm">
          <div class="layui-form-item">
            <div class="layui-inline">
              <label class="layui-form-label">客户</label>
              <div class="layui-input-inline">
                <input type="hidden" name="id" />
                <select name="customerId" id="data_customerid" lay-filter="data_customerid" class="customerSel">
                  <option value ="">请选择客户</option>
                </select>
              </div>
            </div>
            <div class="layui-inline">
              <label class="layui-form-label">商品名称</label>
              <div class="layui-input-inline">
                <input type="hidden" name="id" />
                  <select name="goodsId" id="data_goodsid_update" class="goodsSel">
                    <option value ="">请选择商品</option>
                  </select>
              </div>
            </div>
          </div>
          <div class="layui-form-item">
            <div class="layui-inline">
            <label class="layui-form-label">销售数量</label>
            <div class="layui-input-inline">
              <input type="text" name="number" lay-verify="required|number" autocomplete="off" class="layui-input">
            </div>
            </div>
            <div class="layui-inline">
              <label class="layui-form-label">销售价格</label>
              <div class="layui-input-inline">
                <input type="text" name="salesPrice" lay-verify="required|number" autocomplete="off" class="layui-input">
              </div>
            </div>
          </div>
          <div class="layui-form-item">
            <label class="layui-form-label">支付类型</label>
            <div class="layui-input-block">
              <input type="radio" name="payType" value="支付宝" title="支付宝" checked="">
              <input type="radio" name="payType" value="微信" title="微信">
              <input type="radio" name="payType" value="银联" title="银联">
            </div>
          </div>
          <div class="layui-form-item">
              <label class="layui-form-label">备注</label>
              <div class="layui-input-block">
                <textarea placeholder="请输入备注" name="remark" class="layui-textarea"></textarea>
              </div>
          </div>
          <div class="layui-form-item">
            <div class="layui-input-block" style="text-align: center;">
              <a class="layui-btn " lay-submit=""  lay-filter="doSubmit"><label class="layui-icon layui-icon-release"></label>提交</a>
              <a class="layui-btn layui-btn-warm" onclick="javascript:$('#dataFrm')[0].reset()" lay-filter="data-search-btn"><label class="layui-icon layui-icon-refresh"></label>重置</a>
            </div>
          </div>
        </form>
      </div>
      <!--添加和修改的弹出层结束-->

      <!--退货的弹出层 开始-->
      <div id="backDiv" style="display: none;padding: 0.3125rem">
        <form method="post" class="layui-form layui-form-pane" lay-filter="backDataFrm" id="backDataFrm">
          <div class="layui-form-item">
            <label class="layui-form-label">退货数量</label>
            <div class="layui-input-block">
              <input type="hidden" name="goodsId" id="back_goodsid" />
              <input type="hidden" name="salesId" id="salesId" />
              <input type="hidden" name="customerId" id="customerId" />
              <input type="text" name="number"  lay-verify="required|number|checkgoodsnumber" autocomplete="off" class="layui-input">
            </div>
          </div>
          <div class="layui-form-item">
            <label class="layui-form-label">退货原因</label>
            <div class="layui-input-block">
              <textarea placeholder="请输入退货原因" name="remark" lay-verify="required" class="layui-textarea"></textarea>
            </div>
          </div>
          <div class="layui-form-item">
            <div class="layui-input-block" style="text-align: center;">
              <a class="layui-btn " lay-submit=""  lay-filter="doBack"><label class="layui-icon layui-icon-release"></label>提交</a>
              <a class="layui-btn layui-btn-warm" onclick="javascript:$('#backDataFrm')[0].reset()" lay-filter="data-search-btn"><label class="layui-icon layui-icon-refresh"></label>重置</a>
            </div>
          </div>
        </form>
      </div>
      <!--退货的弹出层 结束-->

    </div>
</div>

<script src="/lib/jquery-3.4.1/jquery-3.4.1.min.js" charset="utf-8"></script>
<script src="/lib/layui-v2.5.5/layui.js" charset="utf-8"></script>
<script src="/js/lay-config.js?v=1.0.4" charset="utf-8"></script>
<script src="/lib/common/jquery.cookie.min.js" charset="utf-8"></script>
<script src="/lib/common/common.js" charset="utf-8"></script>
<script>
    layui.use(['form', 'table','laydate','layer'], function () {
      var $ = layui.jquery,
          form = layui.form,
          table = layui.table;
      var laydate=layui.laydate;
		  var layer=layui.layer;

      //渲染时间选择器
      laydate.render({
        elem:'#startTime',
        type:'datetime'
      });
      laydate.render({
        elem:'#endTime',
        type:'datetime'
      });

      // 加载查询条件里面的客户的下拉列表
      $.get(api+"/customer/getAllEnableCustomer",function(res){
        var search_customerid=$(".customerSel");
        var html="<option value =''>请选择</option>";
        var data=res.data;
        $.each(data,function(index,item){
          html+="<option value ="+item.id+">"+item.customerName+"</option>"
        });
        search_customerid.html(html);
        form.render("select");
      });

      var goodsCache;
      //加载查询条件里面的商品的下拉列表
      $.get(api+"/goods/getAllEnableGoods",function(res){
        var search_goodsid=$(".goodsSel");
        var html="<option value =''>请选择商品</option>";
        var data=res.data;
        goodsCache = data;
        $.each(data,function(index,item){
          html+="<option value ="+item.id+">"+item.goodsName+"["+item.spec+"]"+"</option>"
        });
        search_goodsid.html(html);
        form.render("select");
      });

      var tableIns = table.render({
        elem: '#currentTableId',
        url: api + '/goodsSales/getByPage',
        method: 'post',
        contentType: "application/json; charset=utf-8",
        toolbar:"#toolBar",
        cellMinWidth: true,
        parseData: function(res){ //res 即为原始返回的数据
            return {
                "code": res.code, //解析接口状态
                "msg": res.msg, //解析提示文本
                "count": res.data.total, //解析数据长度
                "data": res.data.records //解析数据列表
            };
        },
        response:{ // 必须配置，否则不加载数据
            statusName:'code', //规定返回的状态码字段为code
            statusCode:200 //规定成功的状态码味200
        },
        done: function(res, curr, count){
            //如果是异步请求数据方式，res即为你接口返回的信息。
            //如果是直接赋值的方式，res即为：{data: [], count: 99} data为当前页数据、count为数据总长度
            // console.log(res);
            //得到当前页码
            // console.log(curr); 
            //得到数据总量
            // console.log(count);
        },
        cols: [[
            {type: "checkbox", width: 50, fixed: "left"},
            {type: "numbers", width: 40, title: '序号', fixed: "left"},
            {field: 'id', width: 80, title: 'ID', hide: true},
            {field: 'goodsName', width: 120, title: '商品'},
            {field: 'customerName', width: 120, title: '客户'},
            {field: 'payType', width: 100, title: '支付方式'},
            {field: 'salesTime', width: 200, title: '销售时间'},
            {field: 'number', width: 120, title: '销售数量'},
            {field: 'salesPrice', width: 120, title: '销售价格'},
            {field: 'operatePerson', width: 100, title: '操作员'},
            {title: '操作', templet: '#tableBar', fixed: "right", align: "center"}
        ]],
        limits: [10, 15, 20, 25, 5],
        limit: 15,
        page: true
      });

      // 监听搜索操作
      form.on('submit(data-search-btn)', function (data) {
        //执行搜索重载
        table.reload('currentTableId', {
          page: {
            curr: 1
          },
          where: {
            queryParams: {
              "customerId": data.field.customerId,
              "goodsId": data.field.goodsId,
              "startTime": data.field.startTime,
              "endTime": data.field.endTime
            }
          },
          async: true
        }, 'data');
        return false;
      });

      var formState = FORM_ADD;
      //提交数据
      form.on("submit(doSubmit)",function(data){
        $.ajax({
          url: url,
          method: formState === FORM_ADD ? "post" : "put",
          async: true,
          contentType: "application/json; charset=utf-8",
          dataType: "json",
          data: JSON.stringify(data.field),
          success:function(res){
            layer.msg(res.msg);
            if(res.code == SUCCESS_CODE) {
              tableIns.reload();
            }
          },
          error:function(){
            layer.msg("操作失败");
          }
        });
        layer.close(mainIndex);
        return false;
      });
 
      //监听表头的事件
      table.on('toolbar(currentTableFilter)', function(obj){
        var checkStatus = table.checkStatus(obj.config.id);
        switch(obj.event){
          case 'delete':
            var checkStatus = table.checkStatus('currentTableId')
                , data = checkStatus.data;
            if(data.length > 0) {
              layer.confirm('真的删除么', function (index) {
                var arr = [];
                //遍历
                data.forEach(function(item){
                  arr.push(item.id)
                });
                $.ajax({
                  url: api + "/goodsSales/deleteByIds",
                  method: "delete",
                  contentType: "application/json; charset=utf-8",
                  data: JSON.stringify(arr),
                  success:function(res){
                    layer.msg(res.msg);
                    tableIns.reload();
                  },
                  error:function(){
                    layer.msg("删除失败");
                  }
                });
                layer.close(index);
              });
            }
          break;
          case 'add':
            openAddGoodsSales();
          break;
        };
      });

      //监听行数据的事件
      table.on('tool(currentTableFilter)', function (obj) {
        var data = obj.data;
        if (obj.event === 'update'){
				  openUpdateGoodsSales(data);
		    } else if(obj.event == 'back') {
          openBack(data);
        }
      });

      //打开退货的弹出层
      function openBack(data){
        mainIndex=layer.open({
          type:1,
          title:"【"+data.goodsName+'】的退货',
          content:$("#backDiv"),
          area:['600px','300px'],
          success:function(index){
            //重置表单
            $("#dataFrm")[0].reset();
            form.val("backDataFrm",data);
            form.val("backDataFrm",{number:'', salesId:data.id});
          }
        });	
      };

      //提交数据
      form.on("submit(doBack)",function(data){
        $.ajax({
          url: api+"/goodsSalesBack/processGoodsBack",
          method: "post",
          async: true,
          contentType: "application/json; charset=utf-8",
          dataType: "json",
          data: JSON.stringify(data.field),
          success:function(res){
            layer.msg(res.msg);
            if(res.code === SUCCESS_CODE) {
              tableIns.reload();
              layer.close(mainIndex);
            }
          },
          error:function(){
              layer.msg("操作失败");
          }
        });
        return false;
      });

      //监听添加弹出层里面的客户的下拉改变事件
      form.on("select(data_customerid)",function(obj){
        var customerid=obj.value;
        var html="<option value =''>请选择商品</option>";
        if(customerid != undefined && customerid != ""){
          $.each(goodsCache, function(i,item){
            if(item.customerId == customerid) {
              html+="<option value ="+item.id+">"+item.goodsName+"["+item.spec+"]"+"</option>"
            }
					});
        }
        var goodsDataSel=$(".goodsDataSel");
        goodsDataSel.html(html);
        form.render("select");
      });
      
      //打开添加销售的弹层
      var mainIndex;
      var url;  //动态的url
      function openAddGoodsSales(){
        formState = FORM_ADD;
        mainIndex=layer.open({
          type:1,
          title:'添加销售',
          content:$("#addOrUpdateDiv"),
          area:['675px','450px'],
          success:function(index){
            url=api + "/goodsSales/addGoodsSales";
            //重置表单
            $("#dataFrm")[0].reset();
            $("#data_customerid").attr("disabled",false);
            $("#data_goodsid_update").attr("disabled",false);
          }
        });	
      };

      function openUpdateGoodsSales(data) {
        formState = FORM_UPDATE;
        mainIndex=layer.open({
          type:1,
          title:'修改销售',
          content:$("#addOrUpdateDiv"),
          area:['675px','450px'],
          success:function(index){
            url=api + "/goodsSales/updateGoodsSales";
            //装载数据表格
            var html="<option value =''>请选择商品</option>";
            $.each(goodsCache, function(i,item){
              html+="<option value ="+item.id+">"+item.goodsName+"["+item.spec+"]"+"</option>"
            });
            var goodsDataSel=$(".goodsDataSel");
            goodsDataSel.html(html);
            form.render("select");

            form.val("dataFrm",data);
            $("#data_customerid").attr("disabled",true);
            $("#data_goodsid_update").attr("disabled",true);
            form.render();
          }
        });	
      };
    });
</script>
<script>

</script>

</body>
</html>